var Promise = require('bluebird');

var gm = require('gm');


var AsyncGm = function(file){
	if(!(this instanceof AsyncGm))
		return new AsyncGm(file);
	this.gm = gm(file);
}

AsyncGm.prototype.getNew = function(file){
	try {
		this.gm = gm(file);
	}
	catch(err){
	} 
	return this;
}

AsyncGm.prototype.sizeAsync = function(){
	var self = this;
	var p = new Promise(function(resolve,reject){
		var gm = self.gm;
		gm.size(function(err, size){
			if(!err){
				resolve(size);
			}else{
				reject(err);
			}
		});
			
	});
	return p.bind(self);
}

AsyncGm.prototype.blur = function(x, y){
	var self = this;
	var gm = self.gm;
	gm.blur(x, y);
	return self;
}

AsyncGm.prototype.quality = function(value){
	var self = this;
	var gm = self.gm;
	gm.quality(value);
	return self;
}

AsyncGm.prototype.in = function(){
	var self = this;
	var gm = self.gm;
	var args = Array.prototype.slice.call(arguments);
	gm.in.apply(gm, args);
	return self;
}

AsyncGm.prototype.command = function(cmd){
	var self = this;
	var gm = self.gm;
	gm.command(cmd);
	return self;
}

AsyncGm.prototype.autoOrient = function(){
	var self = this;
	var gm = self.gm;
	gm.autoOrient();
	return self;
}

AsyncGm.prototype.resize = function(width, height, force){
	var self = this;
	var gm = self.gm;
	gm.resize(width, height, force);
	return self;
}

AsyncGm.prototype.writeAsync = function(path){
	var self = this;
	var p = new Promise(function(resolve, reject){
		var gm = self.gm;
		gm.write(path, function(err){
			if(err){
				reject(err);
			}else{
				resolve();
			}
		});
	});
	return p.bind(this);
}


module.exports = AsyncGm;